<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
     <!-- <el-form-item label="设备" prop="devicesValue">
        <el-select
          v-model="queryParams.devicesValue"
          placeholder="设备"
          clearable
          size="small"
          style="width: 180px">
          <el-option
            v-for="dict in sdDevicesOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="报修时间">
        <el-date-picker
                v-model="dateRange"
                size="small"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
        />
      </el-form-item>

     <el-form-item label="宿舍栋号" prop="buildingNo">
       <el-select
         v-model="queryParams.buildingNo"
         placeholder="宿舍栋号"
         clearable
         size="small"
         style="width: 180px">
         <el-option
           v-for="dict in buildingNoOptions"
           :key="dict.dictValue"
           :label="dict.dictLabel"
           :value="dict.dictValue"
         />
       </el-select>
     </el-form-item>

     <el-form-item label="楼层" prop="storey">
       <el-select
         v-model="queryParams.storey"
         placeholder="宿舍楼层"
         clearable
         size="small"
         style="width: 180px">
         <el-option
           v-for="dict in storeyOptions"
           :key="dict.dictValue"
           :label="dict.dictLabel"
           :value="dict.dictValue"
         />
       </el-select>
     </el-form-item>

      <el-form-item label="宿舍号" prop="dormitoryNo">
        <el-input
          v-model="queryParams.dormitoryNo"
          placeholder="请输入宿舍号"
          clearable
          size="small"
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="报修状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="报修状态"
          clearable
          size="small"
          style="width: 180px">
          <el-option
            v-for="dict in repairStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['smartdor:repair:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['smartdor:repair:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['smartdor:repair:remove']"
        >删除</el-button>
      </el-col>

    </el-row>

    <el-table v-loading="loading" :data="repairList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
     <!-- <el-table-column label="设备" align="center" prop="devicesValue" :formatter="devicesFormat" /> -->
      <el-table-column label="宿舍栋号" align="center" prop="buildingNo" :formatter="buildingNoFormat" />
      <el-table-column label="楼层" align="center" prop="storey" :formatter="storeyFormat" />
      <el-table-column label="宿舍号" align="center" prop="dormitoryNo"/>
      <el-table-column label="状态" align="center" prop="status" :formatter="repairStatusFormat" />
      <el-table-column label="报修说明" align="center" prop="repairDesc" :show-overflow-tooltip="true" />
      <el-table-column label="报修时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>


      <!-- <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
                  v-model="scope.row.status"
                  active-value="1"
                  inactive-value="0"
                  @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column> -->



      <el-table-column label="操作" align="center" width="140" >
        <template slot-scope="scope">
          <el-button
                  size="mini"
                  circle type="info"
                  icon="el-icon-view"
                  @click="handleView(scope.row,scope.index)"
                  v-hasPermi="['smartdor:repair:query']"
          />
          <el-button
                  size="mini"
                  circle type="success"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['smartdor:repair:edit']"
          />
          <el-button
                  size="mini"
                  circle type="danger"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['smartdor:repair:remove']"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 报修详细信息 -->
    <el-dialog title="报修详细信息" :visible.sync="open1" width="700px">
      <el-form ref="form" :model="form" label-width="140px" size="mini">
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备："> {{form.deviceName}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="宿舍栋号：">{{buildingNoFormat(form)}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="宿舍楼层：">{{storeyFormat(form)}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="宿舍号："> {{ form.dormitoryNo }} </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="报修时间："> {{ form.createTime }} </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="报修说明："> {{ form.repairDesc }} </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态：">{{ repairStatusFormat(form) }}</el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="照片：">
            <img width="100" height="100" :src="dialogImageUrl1" alt=""></el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-col v-if="form.repairStatusType==='0'"> -->
        <el-button v-if="form.status==='0'" type="primary" @click="submitForm1">处理</el-button>
        <el-button v-if="form.status==='0' || form.status==='1'" type="primary" @click="submitForm2">已解决</el-button>

        <el-button @click="open1 = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="10" class="mb8">
         <el-col :span="11">
          <el-form-item label="设备" prop="deviceIds">
            <el-select v-model="form.deviceIds" multiple placeholder="请选择">
              <el-option
                      v-for="dict in sdDevicesOptions"
                      :key="dict.id"
                      :label="dict.dictLabel"
                      :value="dict.id"
              />
            </el-select>
          </el-form-item>
         </el-col>
         <el-col :span="11">
          <el-form-item label="宿舍栋号" prop="buildingNo">
           <el-select v-model="form.buildingNo" placeholder="宿舍栋号" :disabled="disabledInput" clearable @change="change1">
             <el-option
               v-for="dict in buildingNoOptions"
               :key="dict.dictValue"
               :label="dict.dictLabel"
               :value="dict.dictValue"/>
           </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="11">
           <el-form-item label="宿舍楼层" prop="storey">
            <el-select v-model="form.storey" placeholder="楼层" :disabled="disabledInput" clearable @change="change2">
              <el-option
                v-for="dict in storeyOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"/>
            </el-select>
           </el-form-item>
           </el-col>
         <el-col :span="11">
           <el-form-item label="宿舍号" prop="bdormitoryId" >
              <el-select v-model="form.bdormitoryId" value-key="id" placeholder="请选择"  :disabled="disabledInput"  >
                <el-option
                        v-for="item in bdormitoryOptions"
                        :key="item.id"
                        :label="item.dormitoryNo"
                        :value="item.id"
                />
              </el-select>
            </el-form-item>
        </el-col>

        <el-col :span="24">
         <el-form-item label="报修说明" prop="repairDesc">
           <el-input type="textarea"  v-model="form.repairDesc" placeholder="请输入报修说明" />
         </el-form-item>
        </el-col>
     </el-row>
        <el-row>
        <el-col :span="1.5">
         <el-form-item label="照片">
				   <el-upload
						   ref="upload"
						    :action="activeUrl"
								:data="form"
								:auto-upload="false"
								multiple="multiple"
								:on-change="uploadChange"
						   name="upload"
						   list-type="picture"
						   :limit="1"
						   :file-list="fileList"
						   :on-exceed="onExceed"
               :headers="headers"
						   :before-upload="beforeUpload"
						   :on-preview="handlePreview"
						   :on-success="handleSuccess"
						   :on-remove="handleRemove">
					   <i class="el-icon-plus"></i>
				   </el-upload>

            <el-input v-model="form.photo" type="hidden" />
			    </el-form-item>
        </el-col>

        </el-row>

				<el-row>
          <el-col :span="1.5" v-if="dialogVisible">
            &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;
          </el-col>
          <el-col :span="1.5" v-if="dialogVisible">
            <img width="100" height="100" :src="dialogImageUrl" alt="">
          </el-col>
        </el-row>

      </el-form>
     <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listRepair, getRepair, addRepair, updateRepair, delRepair, changeRepairStatus} from "@/api/smartdor/repair";
import { getBDormitoryListByCol } from "@/api/basedata/bdormitory";
import { getToken } from '@/utils/auth'


export default {
  name: "BStudent",
  computed:{
    headers(){
      return {
        Authorization: "Bearer " + getToken()
      }
    }
  },
  data() {
    return {
		 //上传的路径
     activeUrl: '',
     //判断是否上传文件
     isHaveFile: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 字典表格数据
      repairList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      open1: false,
      // 日期范围
      dateRange: [],
      // 设备字典
      sdDevicesOptions: [],
      // 宿舍栋号
      buildingNoOptions: [],
      //报修状态
      repairStatusOptions: [],
      // 楼层
      storeyOptions: [],
      // 宿舍号
      bdormitoryOptions: [],

      buildingNo :undefined,
      storey :undefined,
      bdormitoryId :undefined,
      disabledInput:false,

      fileList: [],
      photo:'',

      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        devicesValue: undefined,
        buildingNo: undefined,
        storey: undefined,
        dormitoryNo: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      dialogImageUrl: '',
      dialogImageUrl1: '',
      dialogVisible: false,

      // 表单校验
      rules: {
        deviceIds: [
          { required: true, message: "设备不能为空", trigger: "blur" }
        ],
        buildingNo: [
          { required: true, message: "宿舍栋号不能为空", trigger: "blur" }
        ],
        storey: [
          { required: true, message: "楼层不能为空", trigger: "blur" }
        ],
        bdormitoryId: [
          { required: true, message: "宿舍号不能为空", trigger: "blur" }
        ],
        // photo: [
        //   { required: true, message: '请上传学员照片' }
        // ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_building").then(response => {
      this.buildingNoOptions = response.data;
    });
    this.getDicts("sys_storey").then(response => {
      this.storeyOptions = response.data;
    });
    this.getDicts("repair_status").then(response => {
      this.repairStatusOptions = response.data;
    });
    this.getDicts("dormitory_devices").then(response => {
      this.sdDevicesOptions = response.data;
    });
  },
  methods: {
		//文件状态改变
      uploadChange: function (file, fileList) {
        if (fileList.length > 0) {
          this.isHaveFile = true;
        } else {
          this.isHaveFile = false;
        }
      },

      closeDialog: function (done) {
        this.$refs.upload.clearFiles();
        this.open = false;
        this.reset();
      },
     change1(){
      this.bdormitoryOptions=[];

			 // 获取栋号
			let buildingNo_dictValue=this.buildingNoOptions.find(val=>val.dictValue==this.form.buildingNo).dictValue

			// 获取楼层号
			let storey_dictValue=this.storeyOptions.find(val=>val.dictValue==this.form.storey).dictValue
			if(storey_dictValue==undefined){
        alert("楼层号为空")
				return ;
			}

			getBDormitoryListByCol(buildingNo_dictValue,storey_dictValue).then(response => {
			     this.bdormitoryOptions = response.data;
           console.log(this.bdormitoryOptions);
			   }
			 );

    },
    change2(){
      this.bdormitoryOptions=[];

			 // 获取栋号
			let buildingNo_dictValue=this.buildingNoOptions.find(val=>val.dictValue==this.form.buildingNo).dictValue;

			// 获取楼层号
			let storey_dictValue=this.storeyOptions.find(val=>val.dictValue==this.form.storey).dictValue;
			if(buildingNo_dictValue==undefined){
				return ;
			}

      // 清空宿舍号
      this.$set(this.form, 'bdormitoryId', '')

			getBDormitoryListByCol(buildingNo_dictValue,storey_dictValue).then(response => {
			     this.bdormitoryOptions = response.data;
					 if(this.bdormitoryOptions.length<1){
						 this.form.bdormitoryId='';
					 }
			   }
			 );
    },
    /** 详细按钮操作 */
    handleView(row) {
      this.open1 = true;
      getRepair(row.id).then(response => {
        this.form = response.data;
        })
      //this.form = row;
      this.dialogImageUrl1 = process.env.VUE_APP_BASE_API +'/smartdor/repair/getPhoto.do?id=' + this.form.id + '&width=200&height=200';
    },
	 //文件上传成功的钩子函数
      handleSuccess(res, file) {
        if (this.form.id !== undefined) {
          //alert(res.message);
          console.log(res);
          if (res.code == 200) {
            this.$message({
              type: 'info',
              message: '操作成功',
              duration: 6000
            });
            //关闭弹出层
            this.open = false;
            this.getList();
            this.$refs.upload.clearFiles();
          } else {
            this.$message({
              type: 'info',
              message: '操作失败',
              duration: 6000
            });

          }
        }
       	this.getList();
      },
    //删除文件之前的钩子函数
    handleRemove(file, fileList) {
    		this.$message({
    		  type: 'info',
    			message: '已删除原有图片',
    			duration: 6000
    			});
					this.isHaveFile = false;
    },
    //点击列表中已上传的文件事的钩子函数
    handlePreview(file) {
    },
    //上传的文件个数超出设定时触发的函数
    onExceed(files, fileList) {
    		this.$message({
    		type: 'info',
    		message: '最多只能上传一个图片',
    		duration: 6000
    		});
     },
      //文件上传前的前的钩子函数
      //参数是上传的文件，若返回false，或返回Primary且被reject，则停止上传
    beforeUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isGIF = file.type === 'image/gif';
            const isPNG = file.type === 'image/png';
            const isBMP = file.type === 'image/bmp';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG && !isGIF && !isPNG && !isBMP) {
                  this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!');
            }
            if (!isLt2M) {
                  this.$message.error('上传图片大小不能超过 2MB!');
             }
    },



    /** 查询报修列表 */
    getList() {
      this.loading = true;
      listRepair(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.repairList = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    // 字典设备状态字典翻译
    repairStatusFormat(row, column) {
      return this.selectDictLabel(this.repairStatusOptions, row.status);
    },
    buildingNoFormat(row, column) {
      return this.selectDictLabel(this.buildingNoOptions, row.buildingNo);
    },
    storeyFormat(row, column) {
      return this.selectDictLabel(this.storeyOptions, row.storey);
    },
    bdormitoryFormat(row, column) {
      return this.selectDictLabel(this.bdormitoryOptions, row.bdormitoryId);
    },
    devicesFormat(row, column) {
      return this.selectDictLabel(this.sdDevicesOptions, row.devicesValue);
    },
    // 报修状态修改
    handleStatusChange(row) {
      let text = row.status === "1" ? "已处理" : "报修中";
      this.$confirm('确认要将序号为"' + row.id + '"的报修信息设置为?'+ text, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return changeRepairStatus(row.id, row.status);
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    /** 处理中按钮 */
    submitForm1: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            this.form.status="1";
            updateRepair(this.form.id, this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("此报修单正在成功处理中！");
                this.open1 = false;
                this.getList();
              } else {
                this.msgError(response.message);
              }
            });
          }
        }
      });
    },
    /** 已解决按钮 */
    submitForm2: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            this.form.status="2";
            updateRepair(this.form.id, this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("此报修单已成功解决！");
                this.open1 = false;
                this.getList();
              } else {
                this.msgError(response.message);
              }
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        devicesValue: undefined,
        repairDesc: undefined,
        buildingNo: undefined,
        storey: undefined,
        dormitoryNo: undefined,
        status: "0",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报修信息";
      this.disabledInput=false;

			//新增时隐藏被修改图片
			this.dialogVisible=false;
      this.activeUrl = process.env.VUE_APP_BASE_API +'/smartdor/repair/createRepair';
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRepair(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改报修信息";
        this.disabledInput=true;
				//显示被修改的图片信息
          this.dialogVisible = true;
          this.dialogImageUrl = process.env.VUE_APP_BASE_API +'/smartdor/repair/getPhoto.do?id=' + this.form.id + '&width=200&height=200';
          this.activeUrl = process.env.VUE_APP_BASE_API +'/smartdor/repair/updateAndUpload';
          getBDormitoryListByCol(this.form.buildingNo,this.form.storey).then(response => {
             this.bdormitoryOptions = response.data;
             this.bdormitoryOptions.forEach(a=>{
               a.id = a.id;
             })
            }
          )

      });

    },
    uploadSectionFile(param) {
    				var form = new FormData();
    				if(null !=	param){
    				var fileObj = param.file;
    					form.append("file", fileObj);
    				}
    },
    /** 提交按钮 */
		/*
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateBStudent(this.form.id, this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.message);
              }
            });
          } else {
            addBStudent(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.message);
              }
            });
          }
        }
      });
    },
		*/
	  /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id !== undefined) {
              if (!this.isHaveFile) {
                updateRepair(this.form.id, this.form).then(response => {
                  if (response.code === 200) {
                    this.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  } else {
                    this.msgError(response.message);
                  }
                });
              } else {
                //alert('111 进入修改并且有选择了文件.........')
                if (this.form.devicesValue == undefined) {
                  this.form.devicesValue = '';
                }
                if (this.form.id == undefined) {
                  this.form.id = '';
                }
                /*文件上传，附带表单数据*/
                this.$refs.upload.submit();
              }
            } else {
              if (this.isHaveFile) {
                //alert('新增报修信息，选择了需要上传的文件.............')
                if (this.form.devicesValue == undefined) {
                  this.form.devicesValue = '';
                }
                if (this.form.id == undefined) {
                  this.form.id = '';
                }
                // alert('开始上传...');
                /*文件上传，附带表单数据*/
                this.$refs.upload.submit();
              }else{
                //alert('新增报修信息，并且没有选择文件.............')
                addRepair(this.form).then(response => {
                  if (response.code === 200) {
                    this.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  } else {
                    this.msgError(response.message);
                  }
                });
              }
            }
          }
        });
      },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除报修信息编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delRepair(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    // handleExport() {
    //   const queryParams = this.queryParams;
    //   this.$confirm('是否确认导出所有学员数据项?', "警告", {
    //       confirmButtonText: "确定",
    //       cancelButtonText: "取消",
    //       type: "warning"
    //     }).then(function() {
    //       return exportBStudent(queryParams);
    //     }).then(response => {
    //       this.download(response.msg);
    //     }).catch(function() {});
    // },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>
